package production.practice.common.config;
import java.util.concurrent.*;

/**
 * 线程池配置
 */
public class ThreadPoolConfig {

    private static final int POOL_SIZE;

    static {
        POOL_SIZE = Runtime.getRuntime().availableProcessors() + 1;
    }

    private static final int CORE_POOL_SIZE = POOL_SIZE;

    private static final int MAXIMUM_POOL_SIZE = POOL_SIZE * 2;

    private static final long KEEP_ALIVE_TIME = 1000L;

    private static final TimeUnit TIMEUNIT = TimeUnit.MILLISECONDS;

    //
    private static final BlockingQueue<Runnable> BLOCKING_QUEUE = new ArrayBlockingQueue<>(50);

    private static final ExecutorService executorService = new ThreadPoolExecutor(
            CORE_POOL_SIZE,
            MAXIMUM_POOL_SIZE,
            KEEP_ALIVE_TIME,
            TIMEUNIT,
            BLOCKING_QUEUE,
            r -> {
                Thread thread = new Thread(r);
                thread.setDaemon(true); // 设置守护线程
                return thread;
            },
            new ThreadPoolExecutor.CallerRunsPolicy() //如果添加线程池失败，那么主线程会自己去执行该任务
    );

    public static ExecutorService getThreadPool() {
        return executorService;
    }

}
